package com.demo.provider.controller;


import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

@RestController
public class DemoProviderInfo {

    private static final Logger log = LoggerFactory.getLogger(DemoProviderInfo.class);

    @GetMapping("info")
    public String MsgInfo(){
        log.info("/info This is DemoProvider!");
        return "This is DemoProvider!";
    }

    @Autowired
    private HttpServletRequest request;
    int count = 0;

    @GetMapping("instance/info")
    public String MsgInstanceInfo(@RequestHeader HttpHeaders headers, String zhj){

        System.out.println(request.getServerName()+":"+request.getServerPort());
        count++;
        log.info("/instance/info 响应地址：{} {}", request.getServerName(), request.getServerPort());
        return "第" + count + "次响应服务地址:" + request.getServerName()+":"+request.getServerPort();
    }

    @PostMapping("instance/postinfo")
    public String MsgInstancePostInfo(@RequestHeader HttpHeaders headers, @CookieValue(value="token") String cook,
                                      @RequestParam(value="content") String content){

        System.out.println("从header取出的x-name对应的值为---->"+headers.getFirst("x-name"));
        System.out.println("从query string取出的content对应的值为---->"+content);
        System.out.println("从cookie中取出的token对应的值为---->" + cook);

        Map<String,String> map=new HashMap<String,String>();
        //1.获取所有请求头名称
        Enumeration<String> headerNames = request.getHeaderNames();
        //2.遍历
        while (headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            //根据名称获取请求头的值
            String value = request.getHeader(name);
            map.put(name,value);
        }
        JSONObject jsonObj = new JSONObject(map);
        String resultInfoOuterListStr = jsonObj.toString();

        System.out.println(request.getServerName()+":"+request.getServerPort());
        count++;
        log.info("/instance/postinfo 响应地址：{} {} {}", request.getServerName(), request.getServerPort(), resultInfoOuterListStr);
        return "第" + count + "次响应服务地址:" + request.getServerName()+":"+request.getServerPort()+ "\r\n"+resultInfoOuterListStr;

    }
}
